package com.itheima.reggie.common;

import com.itheima.reggie.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Component
public class FileUploader {

    @Autowired
    MinioConfig minioConfig;

    public String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String objectName = null;
        try {
            String bucketName = minioConfig.getBucketName();
            //创建Minio的连接对象
            MinioClient minioClient = getClient();

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为 reggie 的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            String fileName = file.getOriginalFilename();//合同.pdf
            objectName = UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));

            // 使用putObject上传一个文件到存储桶中。
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(minioConfig.getPath() + objectName)
                    .bucket(bucketName)
                    .contentType(file.getContentType()) //image/jpeg    /text/html
                    .stream(file.getInputStream(), file.getSize(), -1).build();
            minioClient.putObject(objectArgs);

            // 返回上传成功对象  AjaxResult
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        }
        return objectName;
    }

    public InputStream download(String name) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        try {
            String bucketName = minioConfig.getBucketName();
            //创建Minio的连接对象
            MinioClient minioClient = getClient();
            InputStream stream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(minioConfig.getPath() + name).build());
            return stream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 免费提供一个获取Minio连接的方法
     * 获取Minio连接
     *
     * @return
     */
    public MinioClient getClient() {
        MinioClient minioClient =
                MinioClient.builder()
                        // 设置连接哪个monio服务器
                        .endpoint("http://" + minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                        .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                        .build();
        return minioClient;
    }

}
